package vip.wangwenhao.common.util;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import vip.wangwenhao.common.constants.CommonConstants;
import vip.wangwenhao.common.result.Result;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author wwh
 * @date 2020年03月01日 20:09
 */

@Component
public class ServiceUtils {

    private static DiscoveryClient discoveryClient;

    @Resource
    public void setDiscoveryClient(DiscoveryClient discoveryClient) {
        ServiceUtils.discoveryClient = discoveryClient;
    }

    public static <T,F> Result<T> service(String serviceName, String path, F params, Class<T> clazz) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        int i = RandomUtils.nextInt(CommonConstants.ZERO, instances.size());
        ServiceInstance serviceInstance = instances.get(i);
        URI uri = serviceInstance.getUri();
        return HttpUtils.post(uri.toString() + path, params, clazz);
    }
}